package com.iqilu.ksd.utils;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.iqilu.ksd.R;
import com.iqilu.ksd.bean.VersionBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.service.UpdateService;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;

import okhttp3.Call;

/**
 * Created by Coofee on 2016/7/29.
 */
public class UpdateUtils {

    private static final String TAG = "UpdateTool";

    private Context context;
    private boolean showToast = false;
    private String version;
    private ProgressBar progressBar;
    private Dialog progressDialog;
    private TextView txtVersion;
    private TextView txtProgress;

    public UpdateUtils(Context context) {
        this.context = context;
    }

    public UpdateUtils(Context context, boolean showToast) {
        this.context = context;
        this.showToast = showToast;
    }

    public void checkUpdate(final String version) {
        String url = Api.URL_VERSION + "?version=" + version;
        SPUtils.setPrefForLong(context, Config.CHECK_VERSION_TIME, System.currentTimeMillis() / 1000);
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                Log.i(TAG, "checkUpdate..." + response);
                VersionBean result = JSONUtils.requestDetail(response, "data", VersionBean.class);
                if (result != null && !TextUtils.isEmpty(result.getAndroid())) {
                    UpdateUtils.this.version = result.getAndroidversion();
                    showDialog(result.getAndroid());
                } else {
                    if (showToast) {
                        Toast.makeText(context, R.string.setting_update_latest, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    private void showDialog(final String url) {
        final String urlGetApp = url;
        final MaterialDialog dialog = new MaterialDialog(context);
        dialog.content(context.getString(R.string.update_description))
                .btnText(context.getString(R.string.update_cancel), context.getString(R.string.ensure))
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
//                        showProgress();
//                        downLoad(url);
                        toUpdate(url);
                        dialog.dismiss();
                    }
                }
        );
    }

    private void toUpdate(String url) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            Intent intent = new Intent(context, UpdateService.class);
            intent.putExtra("url", url);
            context.startService(intent);
            Toast.makeText(context,R.string.update_async,Toast.LENGTH_SHORT).show();
        } else {
            Intent intent = new Intent();
            intent.setAction("Android.intent.action.VIEW");
            Uri uri = Uri.parse(url);
            intent.setData(uri);
            context.startActivity(intent);
        }
    }

    private void showProgress() {
        progressDialog = new Dialog(context);
        progressDialog.setCancelable(false);
        progressDialog.setContentView(R.layout.dialog_download);
        progressDialog.show();
        WindowManager.LayoutParams p = progressDialog.getWindow().getAttributes();
        p.width = (int) (ScreenUtils.getScreenWidth(context) * 0.9);
        Window window = progressDialog.getWindow();
        window.setAttributes(p);
        progressBar = (ProgressBar) progressDialog.findViewById(R.id.progressBar);
        txtVersion = (TextView) progressDialog.findViewById(R.id.txt_version);
        txtProgress = (TextView) progressDialog.findViewById(R.id.txt_progress);
    }

    private void downLoad(String url) {
        String path = CacheUtils.getCacheDir(context);
        String name = "" + System.currentTimeMillis() + ".apk";
        OkHttpUtils.get().url(url).tag(this).build().execute(new FileCallBack(path, name) {
            @SuppressLint({"StringFormatInvalid", "StringFormatMatches"})
            @Override
            public void inProgress(float progress, long total, int id) {
                super.inProgress(progress, total, id);
                int mProgress = (int) (total * progress);
                int mTotal = (int) total;
                progressBar.setProgress((int) (progress * 100));
                txtVersion.setText(String.format(context.getString(R.string.update_download), "" + version));
                txtProgress.setText(String.format(context.getString(R.string.update_download_progress, "" + mProgress, "" + mTotal)));
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                progressDialog.dismiss();
                Toast.makeText(context, R.string.update_download_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(File response, int id) {
                progressDialog.dismiss();
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setDataAndType(Uri.fromFile(response), "application/vnd.android.package-archive");
                context.startActivity(i);
            }
        });
    }
}
